#!/data/data/com.termux/files/usr/bin/bash
# #环境变量 任何终端均可调用termux命令
# export SHELL=/data/data/com.termux/files/usr/bin/bash
# export LD_PRELOAD=/data/data/com.termux/files/usr/lib/libtermux-exec.so
# export LD_LIBRARY_PATH=/data/data/com.termux/files/usr/lib
# export PATH=$PATH:/data/data/com.termux/files/usr/bin
# export HOME=/data/data/com.termux/files/home
# export TMPDIR=/data/data/com.termux/files/usr/tmp

# 颜色配置
if [ -t 1 ]; then
    NC='\033[0m' # 重置颜色
    ORANGE='\033[1;38;5;208m'
    GREEN='\033[1;32m'
    RED='\033[1;31m'
    CYAN='\033[1;36m'
    YELLOW='\033[1;33m'
    spin=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')
else
    NC=''; ORANGE=''; GREEN=''; RED=''; CYAN=''; YELLOW=''; spin=('*' '*' '*')
fi

total_steps=7
current_step=0
declare -a failed_task_msgs=()
declare -a failed_task_cmds=()

# 动态旋转指示器
spinner() {
    local pid=$1
    local task_msg="$2"
    local delay=0.1
    local i=0
    while kill -0 $pid 2>/dev/null; do
        i=$(( (i+1) % 10 ))
        printf "\r  ${YELLOW}%-1s${NC} ${CYAN}%-34s${YELLOW}%-18s" "${spin[$i]}" "$task_msg" "[ 处理中 ]"
        sleep $delay
    done
    printf "\r\033[K"
}

# 步骤显示函数
show_progress() {
    ((current_step++))
    echo -e "\n${ORANGE}▌${NC} [${YELLOW}${current_step}/${total_steps}${NC}] ${YELLOW}$1${NC}"
}

# 任务执行封装
run_task() {
    local task_msg="$1"
    local cmd="$2"
    
    printf "\r  ${YELLOW}⠿${NC} ${CYAN}%-34s${YELLOW}%-18s" "$task_msg" "[ 启动 ]"
    
    (eval "$cmd") >/dev/null 2>&1 &
    local pid=$!
    
    spinner $pid "$task_msg" &
    local spinner_pid=$!
    
    wait $pid
    local result=$?
    kill $spinner_pid 2>/dev/null
    
    if [ $result -eq 0 ]; then
        printf "\r  ${GREEN}✓${NC} ${CYAN}%-34s${GREEN}%-18s${NC}\n" "$task_msg" "[ 已成功 ]"
    else
        printf "\r  ${RED}✗${NC} ${CYAN}%-34s${RED}%-18s${NC}\n" "$task_msg" "[ 已失败 ]"
        failed_task_msgs+=("$task_msg")
        failed_task_cmds+=("$cmd")
    fi
}

# ========================
# 主程序开始
# ========================

clear
echo -e "${ORANGE}
▛▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▜
▌  ███████╗███████╗██████╗  ██████╗ 
▌  ╚══███╔╝██╔════╝██╔══██╗██╔═══██╗
▌    ███╔╝ █████╗  ██████╔╝██║   ██║
▌   ███╔╝  ██╔══╝  ██╔══██╗██║   ██║
▌  ███████╗███████╗██║  ██║╚██████╔╝
▌  ╚══════╝╚══════╝╚═╝  ╚═╝ ╚═════╝ 
▌ 名称: ZeroTermux 终极部署环境搭建
▌ 版本: v6.0 | 作者: 渐行渐远渐陌生
▌ 启动: $(date +'%Y-%m-%d %H:%M:%S')
▙▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▟${NC}"

#无用，最好的办法是安装时候手动切换源 # --------------------------------------------------
# show_progress "配置软件源"
# run_task "备份主镜像源" '[ -f $PREFIX/etc/apt/sources.list ] && cp $PREFIX/etc/apt/sources.list $PREFIX/etc/apt/sources.list.bak'
# run_task "备份游戏源" '[ -f $PREFIX/etc/apt/sources.list.d/game.list ] && cp $PREFIX/etc/apt/sources.list.d/game.list $PREFIX/etc/apt/sources.list.d/game.list.bak'
# run_task "备份科学源" '[ -f $PREFIX/etc/apt/sources.list.d/science.list ] && cp $PREFIX/etc/apt/sources.list.d/science.list $PREFIX/etc/apt/sources.list.d/science.list.bak'

# run_task "设置主镜像源" '
# mkdir -p $PREFIX/etc/apt;
# sed -i "s/^deb/# deb/g" $PREFIX/etc/apt/sources.list 2>/dev/null;
# echo -e "# The main termux repository:
# deb https://mirrors.tuna.tsinghua.edu.cn/termux/termux-packages-24 stable main" > $PREFIX/etc/apt/sources.list'

# run_task "设置游戏源" '
# mkdir -p $PREFIX/etc/apt/sources.list.d;
# sed -i "s/^deb/# deb/g" $PREFIX/etc/apt/sources.list.d/game.list 2>/dev/null;
# echo -e "# The termux game repository:
# deb https://mirrors.tuna.tsinghua.edu.cn/termux/game-packages-24 games stable" > $PREFIX/etc/apt/sources.list.d/game.list'

# run_task "设置科学源" '
# mkdir -p $PREFIX/etc/apt/sources.list.d;
# sed -i "s/^deb/# deb/g" $PREFIX/etc/apt/sources.list.d/science.list 2>/dev/null;
# echo -e "# The termux science repository:
# deb https://mirrors.tuna.tsinghua.edu.cn/termux/science-packages-24 science stable" > $PREFIX/etc/apt/sources.list.d/science.list'

# 原来部署autojs时的办法
# sed -i 's@^\(deb.*stable main\)$@#\1\ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/termux-packages-24 stable main@' $PREFIX/etc/apt/sources.list
# sed -i 's@^\(deb.*games stable\)$@#\1\ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/game-packages-24 games stable@' $PREFIX/etc/apt/sources.list.d/game.list
# sed -i 's@^\(deb.*science stable\)$@#\1\ndeb https://mirrors.tuna.tsinghua.edu.cn/termux/science-packages-24 science stable@' $PREFIX/etc/apt/sources.list.d/science.list


# 设置新源链接后切换源仓库命令
# termux-change-repo -y

# --------------------------------------------------
show_progress "初始化存储权限"
run_task "配置存储访问" "termux-setup-storage -y"

# --------------------------------------------------
show_progress "执行系统升级"
run_task "更新 软件列表" "yes | pkg update"
run_task "升级 系统组件" "yes | pkg upgrade"

# --------------------------------------------------
show_progress "安装核心工具"
core_tools=(wget zip unzip which termux-tools git openssl proot binutils aapt aapt2 tsu)
for tool in "${core_tools[@]}"; do
    if command -v "$tool" &>/dev/null; then
        printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "安装 $tool" "[ 已存在 ]"
    else
        run_task "安装 $tool" "pkg install $tool -y"
    fi
done

# --------------------------------------------------
show_progress "配置JAVA环境"
# 检查是否存在 OpenJDK 17
if java -version 2>&1 | grep -q "openjdk version \"17"; then
    printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "安装 java" "[ 已存在 ]"
else
    run_task "安装 java" "pkg install openjdk-17 -y"
fi


# --------------------------------------------------
show_progress "配置Python环境"
if command -v python3 &>/dev/null; then
    printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "安装 Python3" "[ 已存在 ]"
else
    run_task "安装 Python3" "pkg install python -y"
fi

if { command -v pip3 || command -v pip; } &>/dev/null; then
    printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "安装 PIP" "[ 已存在 ]"
else
    run_task "安装 PIP" "pkg install python-pip -y"
fi

if command -v pip3 >/dev/null 2>&1 && pip3 show flask >/dev/null 2>&1; then
    printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "安装 Flask" "[ 已存在 ]"
else
    run_task "安装 Flask" "pip3 install flask"
fi

# --------------------------------------------------
show_progress "配置逆向工具"
if [ -f "$PREFIX/bin/apktool" ]; then
    printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "下载 APKTool" "[ 已存在 ]"
else
    run_task "下载 APKTool" "wget -q --show-progress --progress=bar https://gitee.com/jianxingjiany/cloud-based-files/raw/master/apktool -O $PREFIX/bin/apktool"
fi

if [ -f "$PREFIX/bin/apktool.jar" ]; then
    printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "下载 apktool.jar" "[ 已存在 ]"
else
    run_task "下载 apktool.jar" "wget -q --show-progress --progress=bar https://bitbucket.org/iBotPeaches/apktool/downloads/apktool_2.11.1.jar -O $PREFIX/bin/apktool.jar"
fi

if [ -x "$PREFIX/bin/apktool" ] && [ -x "$PREFIX/bin/apktool.jar" ]; then
    # printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "设置执行权限" "[ 已生效 ]"
    printf "\r  ${CYAN}⠿${NC} ${CYAN}%-34s${CYAN}%-18s${NC}\n" "设置 执行权限" "[ 已存在 ]"
else
    run_task "设置执行权限" "chmod +x $PREFIX/bin/apktool*"
fi

# --------------------------------------------------
show_progress "验证安装结果"
declare -A tools=(
    [wget]="GNU Wget"
    [git]="git version"
    [python3]="Python 3"
    [java]="openjdk"
    [apktool]="Apktool"
    [aapt]="Android Asset Packaging Tool"
    [zip]="Zip"
    [unzip]="UnZip"
    [which]="which"
    [tsu]="tsu"
)

echo
for tool in "${!tools[@]}"; do
    if command -v $tool &>/dev/null; then
        printf "  ${CYAN}%-18s${GREEN} ✔ %-24s${NC}\n" "$tool" "(${tools[$tool]})"
    else
        printf "  ${CYAN}%-18s${RED} ✖ %-24s${NC}\n" "$tool" "(缺失)"
    fi
done

# ========================
# 完成报告
# ========================
echo -e "\n${ORANGE}
▛▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▜
▌ 完成时间: $(date +'%H:%M:%S')"
if [ ${#failed_task_msgs[@]} -eq 0 ]; then
    echo -e "▌ ${GREEN}所有组件安装成功!${NC}"
else
    echo -e "▌ ${RED}以下组件安装失败:"
    printf '▌   - %s\n' "${failed_task_msgs[@]}"
fi
echo -e "${ORANGE}▙▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▟${NC}"

# 失败步骤重试模块
if [ ${#failed_task_msgs[@]} -ne 0 ]; then
    echo -e "\n${ORANGE}部分步骤安装失败，以下是失败的步骤及其安装命令：${NC}"
    for i in "${!failed_task_msgs[@]}"; do
        echo -e "  ${RED}✗${NC} ${CYAN}${failed_task_msgs[$i]}${NC}"
        echo -e "      命令: ${YELLOW}${failed_task_cmds[$i]}${NC}"
    done
    
    echo -ne "\n${GREEN}是否要尝试重新安装所有失败步骤？(输入 y 重试，其他键退出) ${NC}"
    read -r retry_answer
    if [[ "$retry_answer" =~ ^[Yy]$ ]]; then
        echo -e "\n${GREEN}正在重试失败的步骤...${NC}"
        for i in "${!failed_task_msgs[@]}"; do
            task_msg="${failed_task_msgs[$i]}"
            cmd="${failed_task_cmds[$i]}"
            echo -e "\n${CYAN}重新安装: ${task_msg}${NC}"
            eval "$cmd"
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}✓ 重试成功: ${task_msg}${NC}"
            else
                echo -e "${RED}✗ 重试失败: ${task_msg}${NC}"
            fi
        done
    fi
fi